package main

import (
	"fmt"
	"io"
	"net/http"
	"log"
)

const form = `
<html>
<body>
<form action="#" method="post" name="bar">
    <input type="text" name="in" />
    <input type="text" name="in" />
    <input type="submit" value="Submit" />
</form>
</body>
</html>`

func logPanics(handle http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		defer func() {
			if x := recover(); x != nil {
				log.Println(request.RemoteAddr, "捕获到异常:", x)
			}
		}()
		// 上面先处理panic，再接着下面调用业务逻辑
		handle(writer, request)
	}
}

func FormServer(w http.ResponseWriter, request *http.Request) {
	// 原本的处理函数的内容
	w.Header().Set("content-Type", "text/html")
	switch request.Method {
	case "GET":
		io.WriteString(w, form)
	case "POST":
		request.ParseForm()
		io.WriteString(w, request.FormValue("in"))  // 一般去一个值，就用这个方法
	}
	// 搞个panic出来
	zero := 0
	tmp := 1 / zero
	io.WriteString(w, string(tmp))
}

func main() {
	// http.HandleFunc("/form", FormServer)
	http.HandleFunc("/form", logPanics(FormServer))  // 把处理函数传给自己写的封装了panic处理的函数里
	if err := http.ListenAndServe(":8000", nil); err != nil {
		fmt.Println("监听端口ERROR:", err)
	}
}